import Vue from 'vue'
import Router from 'vue-router'
import { routes, list, usersRoute } from './routes'
import { getCookie } from "../assets/js/cookie"


Vue.use(Router)

// 解决点击相同路由的报错问题
// 获取原型对象上的push函数
const originalPush = Router.prototype.push
// 修改原型对象中的push方法
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
const router = new Router({
  routes,
  // mode: "history",

})


// router.beforeEach((to,from,next) => {
//   if(to.path !== '/login') {
//     console.log(document.cookie)

//   } else {
//     next()
//   }
// })

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
    if (getCookie("campus_token") !== undefined) { //判断本地是否存在access_token
      next();
    } else {
      if (to.path === '/login') {
        next();
      } else {
        next({
          path: '/login'
        })
      }
    }
  }
  else {
    next();
  }
  if (to.fullPath == "/login") {
    if (getCookie("campus_token") !== undefined) {
      next({
        path: from.fullPath
      });
    } else {
      next();
    }
  }
});



function getArrEqual(list, usersRoute) {
  const routesArr = router.options.routes
  for (let i = 0; i < usersRoute.length; i++) {
    for (let j = 0; j < list.length; j++) {
      if (list[j].path === usersRoute[i]) {
        routesArr[2].children.push(list[j]);
      }
    }
  }
}
//动态添加路由规则 
export const initDynamicRoutes = () => {
  const routesArr = router.options.routes
  let menuList = JSON.parse(sessionStorage.getItem("menu"))
  if (!menuList) return
  getArrEqual(list, usersRoute())
  //让该路由规则重新起作用
  router.addRoutes(routesArr)
}


export default router